<template>
  <div class="appTemplate">
    <Header :title="'起步案例-立方体旋转'" :back="true"/>
    <main ref="threeView" class="main"></main>
    <Footer />
  </div>
</template>

<script setup lang="ts">
import Header from '@/components/Header.vue';
import Footer from '@/components/Footer.vue';
import {onMounted, ref} from "vue";
// 导入整个 three.js核心库
import * as THREE from 'three';
// 导入判断WebGL工具
import WebGL from "@/utils/WebGL";
// 定义three场景显示区域
const threeView = ref();

// 创建场景
const scene = new THREE.Scene();
// 创建相机镜头
// 视野角度（fov）长宽比（aspect）近截面（near）远截面（far）
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 500);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();

// 画立方体
const drawCube = () => {
  const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  return new THREE.Mesh(geometry, material);
}
const cube = drawCube();
// 将立方体添加到场景中
scene.add( cube );

camera.position.z = 2;

// 循环动画
const animate = () => {
  requestAnimationFrame( animate );
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render( scene, camera );
}

onMounted(() => {
  if (WebGL.isWebGLAvailable()) {
    renderer.setSize(threeView.value.offsetWidth - 15, threeView.value.offsetHeight - 15, true);
    threeView.value.appendChild(renderer.domElement)
    animate();
  } else {
    const warning = WebGL.getWebGLErrorMessage();
    threeView.value.appendChild(warning)
  }
})


</script>

<style scoped>

</style>